﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Project.DTO;
using Project.IService;
using Project.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Project.WebAPI.Controllers
{
    
    [Route("api/[controller]")]
    [ApiController]
    [Authorize(Roles = "Employer")]
    public class PriceTemplateController : ControllerBase
    {
        private readonly IPriceTemplateService templateService;
        private readonly IPriceTemplateItemService itemService;
        private readonly IMapper mapper;

        public PriceTemplateController(
            IPriceTemplateService templateService,
            IPriceTemplateItemService itemService,
            IMapper mapper
            )
        {
            this.templateService = templateService;
            this.itemService = itemService;
            this.mapper = mapper;
        }

        /// <summary>
        /// 查询当前用户的价格模板列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetList(int pageSize = 8, int pageIndex = 1)
        {
            var userId = Guid.Parse(HttpContext.User.Claims.FirstOrDefault(n => n.Type == "Id").Value);
            int total;
            var list = await templateService.GetList(t => t.UserId == userId, pageSize, pageIndex, out total, o => o.CreateAt)
                .Select(n => new { n.Id, n.Title, n.UpdateAt, n.IsDefault })
                .ToListAsync();
            return Ok(new { list, total });

        }

        /// <summary>
        /// 价格模板下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("SelectList")]
        public async Task<IActionResult> GetSelectList()
        {
            var userId = Guid.Parse(HttpContext.User.Claims.FirstOrDefault(n => n.Type == "Id").Value);
            var list = await templateService.GetList(t => t.UserId == userId)
                .Select(n => new { n.Id, n.Title,  n.IsDefault })
                .ToListAsync();
            return Ok(list);
        }

        /// <summary>
        /// 查看模板信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> Get(Guid id)
        {
            if (await templateService.ExistsAsync(n => n.Id == id))
                return NotFound("id不存在！");
            var tmp = await templateService.GetEntityAsync(n=>n.Id==id);
            return Ok(new { tmp.Id,tmp.Title,tmp.CreateAt,tmp.IsDefault, 
                items= tmp.Items.Where(i=>i.IsDeleted==false)
                    .Select(i=>new { i.Id,i.ProductId,i.Product.Title,i.Price,i.Type })});
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Post(PriceTemplatePost dto)
        {
            var userId = Guid.Parse(HttpContext.User.Claims.FirstOrDefault(n => n.Type == "Id").Value);
            
            var tmp = new PriceTemplate()
            {
                UpdateAt = DateTime.Now,
                Title = dto.Title,
                IsDefault = dto.IsDefault,
                UserId = userId,
                Items=mapper.Map<List<PriceTemplateItem>>(dto.Items)
            };
            await templateService.AddAsync(tmp);

            // 如果当前设为默认
            if (dto.IsDefault)
            {
                templateService.SetDefault(tmp.Id);
            }

            return Ok("添加完成！");
        }

        /// <summary>
        /// 设置默认模板
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPatch("Default/{id}")]
        public IActionResult SetDefault(Guid id)
        {
            templateService.SetDefault(id);
            return Ok("设置完成！");
        }

        /// <summary>
        /// 修改模板标题
        /// </summary>
        /// <param name="id"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        [HttpPatch("{id}")]
        public async Task<IActionResult> SetTitle(Guid id,string title)
        {
            var tmp = new PriceTemplate() { Id = id, Title = title, UpdateAt = DateTime.Now };
            int rst= await templateService.EditAsync(tmp);
            if (rst > 0)
                return Ok("修改完成！");
            return BadRequest("错误请求，请核对Id");
        }

        /// <summary>
        /// 给价格模板添加产品项
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("Item")]
        public async Task<IActionResult> AddItem(PriceTemplateItemPost dto)
        {
            await itemService.AddAsync<PriceTemplateItemPost>(dto);
            return Ok("添加完成！");
        }

        /// <summary>
        /// 删除项
        /// </summary>
        /// <param name="itemId"></param>
        /// <returns></returns>
        [HttpDelete("Item/{itemId}")]
        public async Task<IActionResult> RemoveItem(Guid itemId)
        {
            await itemService.MarkDeleteAsync(itemId);
            return Ok("删除完成！");
        }

        /// <summary>
        /// 修改价格项
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut("Item/{id}")]
        public async Task<IActionResult> EditItem(Guid id, PriceTemplateItemPut dto)
        {
            if (id != dto.Id)
                return BadRequest("非法请求！");
            var item = mapper.Map<PriceTemplateItem>(dto);
            await itemService.EditAsync(item);
            return Ok("修改完成");
        }


    }
}
